/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package SubsistemaPaciente.Fichas;

import SubsistemaPaciente.Fichas.FichaMedicoGeneral;
import clienteSandraParada.Login;
import clienteSandraParada.Mensajeria;
import com.itextpdf.awt.geom.Dimension;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.ScrollPane;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import ordenar.Ordenar;
import service.EvolucionMedicoGeneral;
import service.Paciente;
import service.Usuario;

/**
 *
 * @author Rodrigo
 */
public class DialogoInfoFichaMedicoGeneral extends javax.swing.JDialog {

    /**
     * Creates new form DialogoInfoPaciente
     */
    private FichaMedicoGeneral ficha;
    private Long idFicha;

    public DialogoInfoFichaMedicoGeneral(java.awt.Frame parent, boolean modal, FichaMedicoGeneral ficha) throws FileNotFoundException, IOException {

        super(parent, modal);
        initComponents();
        setIconImage(new ImageIcon(getClass().getResource("/GUI/Img/logo2.png")).getImage());
        this.ficha = ficha;
        this.inhabilitarCamposAutomaticos();
        this.MouseListenerTabla();
        this.direccion.cargar();
        this.ocultarColumnaID();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel1 = new javax.swing.JPanel();
        direccion = new componentes.Direccion();
        jPanel2 = new javax.swing.JPanel();
        jLabel9 = new javax.swing.JLabel();
        rut = new componentes.Rut();
        campoNombres = new javax.swing.JTextField();
        campoApellidoPat = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        campoApellidoMat = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        telefono = new componentes.Telefono();
        jLabel4 = new javax.swing.JLabel();
        fechaIngreso = new com.toedter.calendar.JDateChooser();
        fechaNacimiento = new javax.swing.JTextField();
        prevision = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jLabel17 = new javax.swing.JLabel();
        jLabel22 = new javax.swing.JLabel();
        jLabel23 = new javax.swing.JLabel();
        peso = new componentes.Numeros();
        talla = new componentes.Numeros();
        imc = new componentes.Numeros();
        pa = new componentes.Numeros();
        fc = new componentes.Numeros();
        temperatura = new componentes.Numeros();
        jPanel6 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        diagnostico = new javax.swing.JTextArea();
        jLabel6 = new javax.swing.JLabel();
        jPanel5 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        antecedentes = new javax.swing.JTextArea();
        jPanel7 = new javax.swing.JPanel();
        jScrollPane5 = new javax.swing.JScrollPane();
        indicaciones = new javax.swing.JTextArea();
        botonAceptar = new javax.swing.JButton();
        botonCancelar = new javax.swing.JButton();
        mensajeriaInformacion = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        alergias = new javax.swing.JTextArea();
        jPanel8 = new javax.swing.JPanel();
        jScrollPane6 = new javax.swing.JScrollPane();
        tablaEvoluciones = new javax.swing.JTable();
        agregarPrograma1 = new javax.swing.JButton();
        modificarPrograma1 = new javax.swing.JButton();
        jLabel24 = new javax.swing.JLabel();
        hasta = new com.toedter.calendar.JDateChooser();
        desde = new com.toedter.calendar.JDateChooser();
        jLabel21 = new javax.swing.JLabel();
        verEvolucion = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);

        jScrollPane1.setPreferredSize(new java.awt.Dimension(999, 629));

        jPanel1.setPreferredSize(new java.awt.Dimension(1000, 630));

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos paciente"));

        jLabel9.setText("Rut:");

        jLabel10.setText("Nombres:");

        jLabel11.setText("Apellido paterno:");

        jLabel12.setText("Apellido materno:");

        jLabel2.setText("Fecha nacimiento:");

        jLabel3.setText("Previsión:");

        jLabel1.setText("Telefono:");

        jLabel4.setText("Fecha ingreso:");

        jLabel5.setText("*");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel9)
                    .addComponent(jLabel10)
                    .addComponent(jLabel11)
                    .addComponent(jLabel12))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(campoApellidoMat)
                    .addComponent(campoApellidoPat)
                    .addComponent(campoNombres)
                    .addComponent(rut, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE))
                .addGap(28, 28, 28)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(prevision)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(fechaIngreso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(fechaNacimiento, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE)
                    .addComponent(telefono, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(20, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(rut, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(campoNombres, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel10)
                            .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(campoApellidoPat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel11))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(campoApellidoMat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel12)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(fechaNacimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(prevision, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(telefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jLabel5)
                                .addComponent(fechaIngreso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Morbilidad"));

        jLabel7.setText("Peso:");

        jLabel8.setText("Talla:");

        jLabel13.setText("IMC:");

        jLabel17.setText("PA:");

        jLabel22.setText("FC:");

        jLabel23.setText("T°:");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(peso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(12, 12, 12)
                .addComponent(jLabel8)
                .addGap(1, 1, 1)
                .addComponent(talla, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel13)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(imc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel17)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel22)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fc, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel23)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(temperatura, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(temperatura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(fc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8)
                    .addComponent(talla, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(pa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(imc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel3Layout.createSequentialGroup()
                            .addGap(6, 6, 6)
                            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel17)
                                .addComponent(jLabel22)
                                .addComponent(jLabel23)
                                .addComponent(jLabel13)))
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(peso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder("Diagnóstico"));
        jPanel6.setPreferredSize(new java.awt.Dimension(300, 103));

        diagnostico.setColumns(20);
        diagnostico.setRows(5);
        jScrollPane4.setViewportView(diagnostico);

        jLabel6.setText("*");

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 490, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 6, Short.MAX_VALUE)
                .addComponent(jLabel6)
                .addContainerGap())
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Antecedentes personales"));
        jPanel5.setPreferredSize(new java.awt.Dimension(300, 93));

        antecedentes.setColumns(20);
        antecedentes.setRows(5);
        jScrollPane3.setViewportView(antecedentes);

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 497, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(15, Short.MAX_VALUE))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder("Indicaciones"));
        jPanel7.setPreferredSize(new java.awt.Dimension(300, 94));

        indicaciones.setColumns(20);
        indicaciones.setRows(5);
        jScrollPane5.setViewportView(indicaciones);

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 497, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(15, Short.MAX_VALUE))
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                .addContainerGap())
        );

        botonAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Aceptar.png"))); // NOI18N
        botonAceptar.setText("Aceptar");
        botonAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonAceptarActionPerformed(evt);
            }
        });

        botonCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Cancelar.png"))); // NOI18N
        botonCancelar.setText("Cancelar");
        botonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonCancelarActionPerformed(evt);
            }
        });

        mensajeriaInformacion.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        mensajeriaInformacion.setText("Área de mensajería");

        jLabel14.setText("*Campos obligatorios");

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Alergias"));
        jPanel4.setPreferredSize(new java.awt.Dimension(300, 96));

        alergias.setColumns(20);
        alergias.setRows(5);
        jScrollPane2.setViewportView(alergias);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 494, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(18, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(19, Short.MAX_VALUE))
        );

        jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder("Asistencia"));

        tablaEvoluciones.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Sesión", "Fecha", "Comentario"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Long.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaEvoluciones.getTableHeader().setReorderingAllowed(false);
        jScrollPane6.setViewportView(tablaEvoluciones);

        agregarPrograma1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Agregar.png"))); // NOI18N
        agregarPrograma1.setToolTipText("Agregar evolución");
        agregarPrograma1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                agregarPrograma1ActionPerformed(evt);
            }
        });

        modificarPrograma1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Edit2.png"))); // NOI18N
        modificarPrograma1.setToolTipText("Modificar evolución");
        modificarPrograma1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                modificarPrograma1ActionPerformed(evt);
            }
        });

        jLabel24.setText("Hasta:");

        hasta.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                hastaPropertyChange(evt);
            }
        });

        desde.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                desdePropertyChange(evt);
            }
        });

        jLabel21.setText("Desde:");

        verEvolucion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Previsualizar.png"))); // NOI18N
        verEvolucion.setToolTipText("Ver evolución");
        verEvolucion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                verEvolucionActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel8Layout.createSequentialGroup()
                        .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 956, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(verEvolucion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(agregarPrograma1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(modificarPrograma1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(jPanel8Layout.createSequentialGroup()
                        .addComponent(jLabel21)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(desde, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel24)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(hasta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel21)
                    .addComponent(jLabel24)
                    .addComponent(hasta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(desde, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel8Layout.createSequentialGroup()
                        .addComponent(agregarPrograma1)
                        .addGap(9, 9, 9)
                        .addComponent(modificarPrograma1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(verEvolucion))
                    .addComponent(jScrollPane6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel14)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(direccion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 498, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, 534, Short.MAX_VALUE)
                            .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, 534, Short.MAX_VALUE)
                            .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, 534, Short.MAX_VALUE)
                            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, 534, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(botonAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(botonCancelar))
                        .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(mensajeriaInformacion, javax.swing.GroupLayout.DEFAULT_SIZE, 1065, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(13, 13, 13)
                        .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(direccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel14)
                .addGap(6, 6, 6)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botonCancelar)
                    .addComponent(botonAceptar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(mensajeriaInformacion)
                .addGap(28, 28, 28))
        );

        jScrollPane1.setViewportView(jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1077, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 684, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     *
     */
    public void MouseListenerTabla() {
        this.tablaEvoluciones.addMouseListener(new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    EvolucionGeneral evo = new EvolucionGeneral(null, true, ficha.dif);
                    evo.setTitle("Ver Evolucion");
                    evo.configurarBotones("ver");
                    evo.inhabilitarCampos();
                    int[] filasSelec = tablaEvoluciones.getSelectedRows();
                    if (filasSelec.length == 1) { //ha seleccionado una fila de la tabla
                        int fil = filasSelec[0];
                        service.EvolucionMedicoGeneral evolucion = (EvolucionMedicoGeneral) cargarEvolucionMedicoGeneral((Long.parseLong((String) getTablaEvoluciones().getValueAt(fil, 0))));
                        evo.llenarDatosFormularioEvolucion(evolucion);
                        evo.setLocationRelativeTo(null);
                        evo.setVisible(true);
                    } else {
                        JOptionPane.showMessageDialog(null, "Debe seleccionar una fila!", "Advertencia", JOptionPane.WARNING_MESSAGE);
                    }
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        });
    }

    public Long getIdFicha() {
        return idFicha;
    }

    public JTable getTablaEvoluciones() {
        return tablaEvoluciones;
    }

    private void botonAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAceptarActionPerformed
        cambiarEtiquetaMensajeria("Área de mensajería", Color.black);
        if (camposObligatoriosLlenos()) {

            service.Paciente p = (Paciente) cargarPaciente(this.rut.getRut().getText());
            if (p != null) {
                if (botonAceptar.getText().equalsIgnoreCase("Guardar")) {
                    service.FichaMedicoGeneral far = (service.FichaMedicoGeneral) obtenerFichaFarfan(this.idFicha);
                    String anterior = "Rut profesional: " + far.getRutProfesional() + "\n" + "Rut paciente: " + far.getRutPaciente() + "\n" + "Alergias: " + far.getAlergias() + "\n" + "Antecedentes: " + far.getAntedecentes() + "\n" + "Diagnóstico: " + far.getDiagnostico()
                            + "\n" + "FC: " + far.getFc() + "\n" + "Fecha Ingreso: " + far.getFechaIngreso() + "\n" + "Indicaciones: "
                            + far.getIndicaciones() + "\n" + "PA: " + far.getPa() + "\n" + "Peso: " + far.getPeso() + "\n" + "Talla: " + far.getTalla() + "\n" + "Temp: " + far.getTemp();
                    far.setAlergias(this.alergias.getText());
                    far.setAntedecentes(antecedentes.getText());
                    far.setDiagnostico(diagnostico.getText());
                    far.setFc(fc.getNumeros().getText());

                    far.setFechaIngreso(this.capturarFecha(this.fechaIngreso.getDate()));
                    far.setImc(imc.getNumeros().getText());
                    far.setIndicaciones(indicaciones.getText());
                    far.setPa(pa.getNumeros().getText());
                    far.setPeso(peso.getNumeros().getText());
                    far.setRutPaciente(rut.getRut().getText());
                    far.setTalla(talla.getNumeros().getText());
                    far.setTemp(temperatura.getNumeros().getText());
                    far.setValido(true);
                    editarFichaFarfan(far);
                    String nuevo = "Rut profesional: " + far.getRutProfesional() + "\n" + "Rut Paciente: " + far.getRutPaciente() + "\n" + "Alergias: " + far.getAlergias() + "\n" + "Antecedentes: " + far.getAntedecentes() + "\n" + "Diagnóstico: " + far.getDiagnostico()
                            + "\n" + "FC: " + far.getFc() + "\n" + "Fecha Ingreso: " + far.getFechaIngreso() + "\n" + "Indicaciones: "
                            + far.getIndicaciones() + "\n" + "PA: " + far.getPa() + "\n" + "Peso: " + far.getPeso() + "\n" + "Talla: " + far.getTalla() + "\n" + "Temp: " + far.getTemp();
                    registrar(Login.getUser(), "Ficha Médico general", "Modificó ficha a profesional:" + far.getRutProfesional() + "de paciente :" + far.getRutPaciente(), anterior, nuevo);
                    ficha.actualizarTabla();
                    cambiarEtiquetaMensajeria(Mensajeria.mensajeDeAccion("Ficha medicina general", "modificar"), Color.black);
                    this.dispose();
                } else if (botonAceptar.getText().equalsIgnoreCase("Exportar")) {
                    service.Privilegios pri = (service.Privilegios) cargarPrivilegios(Login.getUser().getRut());
                    if (pri.isExportarFichaMedicinaGeneral()) {
                        try {
                            service.FichaMedicoGeneral far = (service.FichaMedicoGeneral) obtenerFichaFarfan(this.idFicha);
                            this.exportarPDF(far);
                            cambiarEtiquetaMensajeria(Mensajeria.mensajeDeAccion("Ficha medicina general", "exportar"), Color.black);
                            this.dispose();
                        } catch (Exception ex) {
                            Logger.getLogger(Paciente.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } else {
                        JOptionPane.showMessageDialog(this, "No tiene permisos para esta acción, \n contacte al administrador para más información");
                    }
                } else if (botonAceptar.getText().equalsIgnoreCase("Agregar")) {
                    boolean duplicada = estaDuplicada(rut.getRut().getText(), Login.getUser().getRut());
                    if (duplicada == false) {
                        service.FichaMedicoGeneral far = new service.FichaMedicoGeneral();
                        // asignarle los valores a far

                        far.setRutProfesional(Login.getUser().getRut());
                        far.setAlergias(this.alergias.getText());
                        far.setAntedecentes(antecedentes.getText());
                        far.setDiagnostico(diagnostico.getText());
                        far.setFc(fc.getNumeros().getText());

                        far.setFechaIngreso(this.capturarFecha(this.fechaIngreso.getDate()));
                        far.setImc(imc.getNumeros().getText());
                        far.setIndicaciones(indicaciones.getText());
                        far.setPa(pa.getNumeros().getText());
                        far.setPeso(peso.getNumeros().getText());
                        far.setRutPaciente(rut.getRut().getText());
                        far.setTalla(talla.getNumeros().getText());
                        far.setTemp(temperatura.getNumeros().getText());
                        far.setValido(true);
                        agregarFichaFarfan(far);
                        String nuevo = "Rut profesional: " + far.getRutProfesional() + "\n" + "Rut Paciente: " + far.getRutPaciente() + "\n" + "Alergias: " + far.getAlergias() + "\n" + "Antecedentes: " + far.getAntedecentes() + "\n" + "Diagnóstico: " + far.getDiagnostico()
                                + "\n" + "FC: " + far.getFc() + "\n" + "Fecha Ingreso: " + far.getFechaIngreso() + "\n" + "Indicaciones: "
                                + far.getIndicaciones() + "\n" + "PA: " + far.getPa() + "\n" + "Peso: " + far.getPeso() + "\n" + "Talla: " + far.getTalla() + "\n" + "Temp: " + far.getTemp();
                        registrar(Login.getUser(), "Ficha Médico general", "Agregó ficha a profesional:" + far.getRutProfesional() + "de paciente :" + far.getRutPaciente(), "No aplica", nuevo);
                        //   ficha.actualizarTabla();
                        cambiarEtiquetaMensajeria(Mensajeria.mensajeDeAccion("Ficha medicina general", "agregar"), Color.black);
                        this.dispose();
                    } else {
                        cambiarEtiquetaMensajeria(Mensajeria.mensajeEntidadExistente("Ficha medicina general"), Color.red);
                    }
                }
            }

        } else {
            cambiarEtiquetaMensajeria(Mensajeria.mensajeCamposObligatorios(), Color.red);
        }
}//GEN-LAST:event_botonAceptarActionPerformed
    public void cambiarEtiquetaMensajeria(String mensaje, Color color) {
        this.mensajeriaInformacion.setText(mensaje);
        this.mensajeriaInformacion.setForeground(color);

    }

    private boolean estaDuplicada(String paciente, String profesional) {
        java.util.List<service.FichaMedicoGeneral> fichas = listarFichasFarfan();

        for (int i = 0; i < fichas.size(); i++) {
            if (fichas.get(i).getRutPaciente().equals(paciente) && fichas.get(i).getRutProfesional().equals(profesional)) {
                return true;
            }
        }
        return false;
    }
    private void botonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonCancelarActionPerformed
        this.dispose();
}//GEN-LAST:event_botonCancelarActionPerformed

    private void agregarPrograma1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_agregarPrograma1ActionPerformed
        // agregar evolucion
        this.cambiarEtiquetaMensajeria("Área de mensajería", Color.black);
        EvolucionGeneral evo = new EvolucionGeneral(null, true, this);
        evo.setTitle("Agregar Evolucion");
        evo.configurarBotones("agregar");
        evo.limpiarFormularioEvolucion();
        evo.agregarDatos(this.contarSesiones());
        evo.habilitarCampos();
        evo.setLocationRelativeTo(null);
        evo.setVisible(true);
}//GEN-LAST:event_agregarPrograma1ActionPerformed

    private void modificarPrograma1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_modificarPrograma1ActionPerformed
        // modificar Evolucion
        this.cambiarEtiquetaMensajeria("Área de mensajería", Color.black);
        EvolucionGeneral evo = new EvolucionGeneral(null, true, this);
        evo.setTitle("Modificar Evolucion");
        evo.configurarBotones("modificar");
        int[] filasSelec = tablaEvoluciones.getSelectedRows();
        if (filasSelec.length == 1) { //ha seleccionado una fila de la tabla
            int fil = filasSelec[0];
            service.EvolucionMedicoGeneral evolucion = (EvolucionMedicoGeneral) cargarEvolucionMedicoGeneral((Long.parseLong((String) getTablaEvoluciones().getValueAt(fil, 0))));
            evo.habilitarCampos();
            evo.llenarDatosFormularioEvolucion(evolucion);
            evo.setLocationRelativeTo(null);
            evo.setVisible(true);
        } else {
            this.cambiarEtiquetaMensajeria("Debe seleccionar una evolución", Color.red);
        }
}//GEN-LAST:event_modificarPrograma1ActionPerformed

    private void hastaPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_hastaPropertyChange
        // TODO add your handling code here:
        this.cambiarEtiquetaMensajeria("Área de Mensajería ", Color.black);
        if (this.desde.getDate() != null && this.hasta.getDate() != null) {
            if (this.desde.getDate().after(this.hasta.getDate())) {
                this.cambiarEtiquetaMensajeria("Rango de fechas erróneas", Color.red);
            }

            actualizarTablaFiltro();

        }
}//GEN-LAST:event_hastaPropertyChange

    private void desdePropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_desdePropertyChange
        // TODO add your handling code here:
        // TODO add your handling code here:
        // if muy necesario ya que al momento de setear una fecha dentro del codigo llama de imediato a este
        //metodo por lo tanto si se setea solo uno va  a tomar el otro null y se caera el programa
        this.cambiarEtiquetaMensajeria("Área de Mensajería ", Color.black);
        if (this.desde.getDate() != null && this.hasta.getDate() != null) {
            if (this.desde.getDate().after(this.hasta.getDate())) {
                this.cambiarEtiquetaMensajeria("Rango de fechas erróneas", Color.red);
            }

            actualizarTablaFiltro();

        }
}//GEN-LAST:event_desdePropertyChange

    private void verEvolucionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_verEvolucionActionPerformed
        // ver evolucion
        this.cambiarEtiquetaMensajeria("Área de mensajería", Color.black);
        EvolucionGeneral evo = new EvolucionGeneral(null, true, this);
        evo.setTitle("Ver Evolucion");
        evo.configurarBotones("ver");
        evo.inhabilitarCampos();
        int[] filasSelec = tablaEvoluciones.getSelectedRows();
        if (filasSelec.length == 1) { //ha seleccionado una fila de la tabla
            int fil = filasSelec[0];
            service.EvolucionMedicoGeneral evolucion = (EvolucionMedicoGeneral) cargarEvolucionMedicoGeneral((Long.parseLong((String) getTablaEvoluciones().getValueAt(fil, 0))));
            evo.llenarDatosFormularioEvolucion(evolucion);
            evo.setLocationRelativeTo(null);
            evo.setVisible(true);
        } else {
            this.cambiarEtiquetaMensajeria("Debe seleccionar una evolución", Color.red);
        }
}//GEN-LAST:event_verEvolucionActionPerformed
    private void actualizarTablaFiltro() {
        this.limpiarTabla();
        List<service.EvolucionMedicoGeneral> evoluciones = listarEvolucionMedicoGeneral();
        Ordenar.ordena(evoluciones, "sesion");
        int j = 0;
        for (int i = 0; i < evoluciones.size(); i++) {
            // si la evolucion corresponde a la ficha creada
            Date d = this.stringToDate(evoluciones.get(i).getFecha());
            if (evoluciones.get(i).getIdFichaMedicoGeneral().equals(this.idFicha) && (this.desde.getDate().before(d) && this.hasta.getDate().after(d) || this.esMismoDia(this.desde.getDate(), d)
                    || this.esMismoDia(this.hasta.getDate(), d))) {
                this.agregarFila();
                tablaEvoluciones.setValueAt(evoluciones.get(i).getId() + "", j, 0);
                tablaEvoluciones.setValueAt(evoluciones.get(i).getSesion(), j, 1);
                tablaEvoluciones.setValueAt(evoluciones.get(i).getFecha() + "", j, 2);
                tablaEvoluciones.setValueAt(evoluciones.get(i).getComentario() + "", j, 3);
                j++;
            }

        }
    }

    private static boolean esMismoDia(Date fecha1, Date fecha2) {
        if (fecha1 == null || fecha2 == null) {
            throw new IllegalArgumentException("Las fechas no pueden ser null");
        }
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(fecha1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(fecha2);
        return isSameDay(cal1, cal2);
    }

    private static boolean isSameDay(Calendar cal1, Calendar cal2) {
        if (cal1 == null || cal2 == null) {
            throw new IllegalArgumentException("Las fechas no pueden ser null");
        }
        return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
    }

    public boolean camposObligatoriosLlenos() {
        if (this.fechaIngreso.getDate() != null
                && !this.diagnostico.getText().equals("")) {
            return true;
        }
        return false;
    }

    public boolean comboValido(JComboBox combo) {
        Boolean b = false;
        if (combo.getSelectedItem() != null) {
            if (combo.getSelectedItem().equals("") || combo.getSelectedItem().equals("Seleccionar")) {
                b = false;
            } else {
                b = true;
            }
        } else {
            b = false;
        }
        return b;
    }

    public String capturarFecha(Date d) {
        Calendar cal = Calendar.getInstance();
        String fecha = "dd-MM-yyyy";
        if (d != null) {
            cal.setTime(d);
            //Dia - mes - año
            fecha = Integer.toString(cal.get(Calendar.DAY_OF_MONTH)) + "-"
                    + Integer.toString(cal.get(Calendar.MONTH) + 1) + "-"
                    + Integer.toString(cal.get(Calendar.YEAR));
        }
        return fecha;
    }

    public Date stringToDate(String strFecha) {
        SimpleDateFormat formatoDelTexto = new SimpleDateFormat("dd-MM-yyyy");
        Date fecha = null;
        try {
            fecha = formatoDelTexto.parse(strFecha);
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        return fecha;
    }

    public String eligeDireccionArchivo() {
        String dirArchivo = "";
        JFileChooser jFileChooser1 = new JFileChooser();
        jFileChooser1.setDialogTitle("Guardar archivo:");
        jFileChooser1.setVisible(true);

        int r = jFileChooser1.showSaveDialog(null);
        if (r == JFileChooser.APPROVE_OPTION) {
            File file = jFileChooser1.getSelectedFile();
            dirArchivo = String.valueOf(file);
        }
        dirArchivo = dirArchivo.replace('\\', '/') + ".pdf";
        return dirArchivo;

    }

    public void abrirArchivo(String direccion) {
        //Abre el documento pdf
        try {
            File file = new File(direccion);
            Desktop.getDesktop().open(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void exportarPDF(service.FichaMedicoGeneral ficha) throws Exception {

        Font fuenteTitulo = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD);
        Font fuenteSubTitulo = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
        Font fuenteTexto = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL);
        JFileChooser jF1 = new javax.swing.JFileChooser();
        String ruta;
        try {
            if (jF1.showSaveDialog(null) == jF1.APPROVE_OPTION) {
                ruta = jF1.getSelectedFile().getAbsolutePath() + ".pdf";
                service.Usuario us = (service.Usuario) cargarUsuario(ficha.getRutProfesional());
                PdfPTable profesional = new PdfPTable(2);
                if (us != null) {
                    profesional.addCell(new PdfPCell(new Paragraph("Rut: ", fuenteTexto)));
                    profesional.addCell(new PdfPCell(new Paragraph(us.getRut(), fuenteTexto)));
                    profesional.addCell(new PdfPCell(new Paragraph("Nombre: ", fuenteTexto)));
                    profesional.addCell(new PdfPCell(new Paragraph(us.getNombres(), fuenteTexto)));
                    profesional.addCell(new PdfPCell(new Paragraph("Apellido Paterno: ", fuenteTexto)));
                    profesional.addCell(new PdfPCell(new Paragraph(us.getApellidoPaterno(), fuenteTexto)));
                    profesional.addCell(new PdfPCell(new Paragraph("Apellido Materno: ", fuenteTexto)));
                    profesional.addCell(new PdfPCell(new Paragraph(us.getApellidoMaterno(), fuenteTexto)));
                    profesional.addCell(new PdfPCell(new Paragraph("Especialidad: ", fuenteTexto)));
                    profesional.addCell(new PdfPCell(new Paragraph("Medicina General", fuenteTexto)));
                }
                PdfPTable tabla = new PdfPTable(2);
                tabla.addCell(new PdfPCell(new Paragraph("Rut: ", fuenteTexto)));
                tabla.addCell(new PdfPCell(new Paragraph(this.rut.getRut().getText(), fuenteTexto)));
                tabla.addCell(new PdfPCell(new Paragraph("Nombre: ", fuenteTexto)));
                tabla.addCell(new PdfPCell(new Paragraph(campoNombres.getText(), fuenteTexto)));
                tabla.addCell(new PdfPCell(new Paragraph("Apellido Paterno: ", fuenteTexto)));
                tabla.addCell(new PdfPCell(new Paragraph(this.campoApellidoPat.getText(), fuenteTexto)));
                tabla.addCell(new PdfPCell(new Paragraph("Apellido Materno: ", fuenteTexto)));
                tabla.addCell(new PdfPCell(new Paragraph(this.campoApellidoMat.getText(), fuenteTexto)));
                tabla.addCell(new PdfPCell(new Paragraph("Fecha de Nacimiento: ", fuenteTexto)));
                tabla.addCell(new PdfPCell(new Paragraph(fechaNacimiento.getText(), fuenteTexto)));
                tabla.addCell(new PdfPCell(new Paragraph("Previsión:  ", fuenteTexto)));
                tabla.addCell(new PdfPCell(new Paragraph(prevision.getText(), fuenteTexto)));
                tabla.addCell(new PdfPCell(new Paragraph("Teléfono:  ", fuenteTexto)));
                tabla.addCell(new PdfPCell(new Paragraph(this.telefono.getTelefono().getText(), fuenteTexto)));
                tabla.addCell(new PdfPCell(new Paragraph("Fecha de Ingreso:  ", fuenteTexto)));
                tabla.addCell(new PdfPCell(new Paragraph(capturarFecha(this.fechaIngreso.getDate()), fuenteTexto)));
                PdfPTable tabla1 = new PdfPTable(2);
                tabla1.addCell(new PdfPCell(new Paragraph("Región: ", fuenteTexto)));
                tabla1.addCell(new PdfPCell(new Paragraph(validarDireccion(direccion.getRegion().getSelectedItem().toString()), fuenteTexto)));
                tabla1.addCell(new PdfPCell(new Paragraph("Provincia: ", fuenteTexto)));
                tabla1.addCell(new PdfPCell(new Paragraph(validarDireccion(direccion.getProvincia().getSelectedItem().toString()), fuenteTexto)));
                tabla1.addCell(new PdfPCell(new Paragraph("Comuna: ", fuenteTexto)));
                tabla1.addCell(new PdfPCell(new Paragraph(validarDireccion(direccion.getComuna().getSelectedItem().toString()), fuenteTexto)));
                tabla1.addCell(new PdfPCell(new Paragraph("Sector: ", fuenteTexto)));
                tabla1.addCell(new PdfPCell(new Paragraph(direccion.getSector().getText(), fuenteTexto)));
                tabla1.addCell(new PdfPCell(new Paragraph("Calle: ", fuenteTexto)));
                tabla1.addCell(new PdfPCell(new Paragraph(direccion.getCalle().getText(), fuenteTexto)));
                tabla1.addCell(new PdfPCell(new Paragraph("Número: ", fuenteTexto)));
                tabla1.addCell(new PdfPCell(new Paragraph(direccion.getNumero().getText(), fuenteTexto)));
                tabla1.addCell(new PdfPCell(new Paragraph("Departamento: ", fuenteTexto)));
                tabla1.addCell(new PdfPCell(new Paragraph(direccion.getDepartamento().getText(), fuenteTexto)));
                tabla1.addCell(new PdfPCell(new Paragraph("Bloque: ", fuenteTexto)));
                tabla1.addCell(new PdfPCell(new Paragraph(direccion.getBloque().getText(), fuenteTexto)));
                PdfPTable tabla2 = new PdfPTable(2);
                tabla2.addCell(new PdfPCell(new Paragraph("Peso: ", fuenteTexto)));
                tabla2.addCell(new PdfPCell(new Paragraph(peso.getNumeros().getText(), fuenteTexto)));
                tabla2.addCell(new PdfPCell(new Paragraph("Talla: ", fuenteTexto)));
                tabla2.addCell(new PdfPCell(new Paragraph(talla.getNumeros().getText(), fuenteTexto)));
                tabla2.addCell(new PdfPCell(new Paragraph("IMC: ", fuenteTexto)));
                tabla2.addCell(new PdfPCell(new Paragraph(imc.getNumeros().getText(), fuenteTexto)));
                tabla2.addCell(new PdfPCell(new Paragraph("PA: ", fuenteTexto)));
                tabla2.addCell(new PdfPCell(new Paragraph(pa.getNumeros().getText(), fuenteTexto)));
                tabla2.addCell(new PdfPCell(new Paragraph("FC: ", fuenteTexto)));
                tabla2.addCell(new PdfPCell(new Paragraph(fc.getNumeros().getText(), fuenteTexto)));
                tabla2.addCell(new PdfPCell(new Paragraph("Temperatura: ", fuenteTexto)));
                tabla2.addCell(new PdfPCell(new Paragraph(temperatura.getNumeros().getText(), fuenteTexto)));
                PdfPTable tabla3 = new PdfPTable(2);
                tabla3.addCell(new PdfPCell(new Paragraph("Alergias: ", fuenteTexto)));
                tabla3.addCell(new PdfPCell(new Paragraph(alergias.getText(), fuenteTexto)));
                tabla3.addCell(new PdfPCell(new Paragraph("Antecedentes personales: ", fuenteTexto)));
                tabla3.addCell(new PdfPCell(new Paragraph(antecedentes.getText(), fuenteTexto)));
                tabla3.addCell(new PdfPCell(new Paragraph("Diagnóstico: ", fuenteTexto)));
                tabla3.addCell(new PdfPCell(new Paragraph(diagnostico.getText(), fuenteTexto)));
                tabla3.addCell(new PdfPCell(new Paragraph("Indicaciones: ", fuenteTexto)));
                tabla3.addCell(new PdfPCell(new Paragraph(indicaciones.getText(), fuenteTexto)));
//                PdfPTable tabla4 = new PdfPTable(3);
//                tabla4.addCell(new PdfPCell(new Paragraph("Sesión: ", fuenteSubTitulo)));
//                tabla4.addCell(new PdfPCell(new Paragraph("Fecha: ", fuenteSubTitulo)));
//                tabla4.addCell(new PdfPCell(new Paragraph("Evolución", fuenteSubTitulo)));
//                for (int i = 0; i < tablaEvoluciones.getRowCount(); i++) {
//                    // si la evolucion corresponde a la ficha creada
//                    tabla4.addCell(new PdfPCell(new Paragraph(tablaEvoluciones.getValueAt(i, 1).toString(), fuenteTexto)));
//                    tabla4.addCell(new PdfPCell(new Paragraph(tablaEvoluciones.getValueAt(i, 2).toString(), fuenteTexto)));
//                    tabla4.addCell(new PdfPCell(new Paragraph(tablaEvoluciones.getValueAt(i, 3).toString(), fuenteTexto)));
//
//                }


                Document document = new Document();
                FileOutputStream ficheroPdf = new FileOutputStream(ruta);
                PdfWriter.getInstance(document, ficheroPdf).setInitialLeading(20);
                document.open();
                document.add(new Paragraph("Historia clínica medicina general", fuenteTitulo));
                document.add(new Paragraph("Información Datos Profesional", fuenteSubTitulo));
                document.add(new Paragraph(" ", fuenteTexto));
                if (us != null) {
                    document.add(profesional);
                }
                document.add(new Paragraph("Información Datos Paciente", fuenteSubTitulo));
                document.add(new Paragraph(" ", fuenteTexto));
                document.add(tabla);
                document.add(new Paragraph(" ", fuenteTexto));
                document.add(new Paragraph("Datos Dirección", fuenteSubTitulo));
                document.add(new Paragraph(" ", fuenteTexto));
                document.add(tabla1);
                document.add(new Paragraph(" ", fuenteTexto));
                document.add(new Paragraph("Morbilidad", fuenteSubTitulo));
                document.add(new Paragraph(" ", fuenteTexto));
                document.add(tabla2);
                document.add(new Paragraph(" ", fuenteTexto));
                document.add(tabla3);
                document.add(new Paragraph(" ", fuenteTexto));
//                document.add(new Paragraph("Evoluciones", fuenteSubTitulo));
//                document.add(new Paragraph(" ", fuenteTexto));
//                document.add(tabla4);
                document.close();
                File f = new File(ruta);
                Desktop.getDesktop().open(f);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * @method utilizado cuando se da el caso de que la direccion de un paciente es "Seleccionar",
     * retorna un ""
     * @param direccion
     * @return
     */
    public String validarDireccion(String direccion) {
        if (direccion.equals("Seleccionar")) {
            return "";
        } else {
            return direccion;
        }

    }

    public JButton getBotonAceptar() {
        return this.botonAceptar;
    }

    public JButton getBotonCancelar() {
        return this.botonCancelar;
    }

    public void inhavilitarRut() {
        this.rut.getRut().setEnabled(false);
    }

    public void cambiarMensajeria(String s) {
        this.mensajeriaInformacion.setText(s);
    }

    public void llenarCampos(service.FichaMedicoGeneral far) {
        this.limpiarCampos();
        this.idFicha = far.getId();
        service.Paciente p = (Paciente) cargarPaciente(far.getRutPaciente());
        rut.getRut().setText(p.getRut());
        campoNombres.setText(p.getNombres());
        campoApellidoPat.setText(p.getApellidoPaterno());
        campoApellidoMat.setText(p.getApellidoMaterno());
        prevision.setText(p.getPrevision());
        fechaNacimiento.setText(p.getFechaNac());
        direccion.getRegion().setSelectedItem((Object) p.getRegion());
        direccion.getProvincia().setSelectedItem((Object) p.getProvincia());
        direccion.getComuna().setSelectedItem((Object) p.getComuna());
        direccion.getSector().setText(p.getSector());
        direccion.getCalle().setText(p.getCalle());
        direccion.getNumero().setText(p.getNumero());
        direccion.getDepartamento().setText(p.getDepartamento());
        direccion.getBloque().setText(p.getBloque());
        telefono.getTelefono().setText(p.getTelefono());
        this.fechaIngreso.setDate(stringToDate(far.getFechaIngreso()));
        // morbilidad
        peso.getNumeros().setText(far.getPeso());
        talla.getNumeros().setText(far.getTalla());
        imc.getNumeros().setText(far.getImc());
        pa.getNumeros().setText(far.getPa());
        fc.getNumeros().setText(far.getFc());
        temperatura.getNumeros().setText(far.getTemp());
        alergias.setText(far.getAlergias());
        antecedentes.setText(far.getAntedecentes());
        diagnostico.setText(far.getDiagnostico());
        indicaciones.setText(far.getIndicaciones());
        this.actualizarTabla();
    }

    public void llenarCamposAutomaticos(service.Paciente p) {
        this.limpiarCamposAutomaticos();
        rut.getRut().setText(p.getRut());
        campoNombres.setText(p.getNombres());
        campoApellidoPat.setText(p.getApellidoPaterno());
        campoApellidoMat.setText(p.getApellidoMaterno());
        prevision.setText(p.getPrevision());
        fechaNacimiento.setText(p.getFechaNac());
        direccion.getRegion().setSelectedItem((Object) p.getRegion());
        direccion.getProvincia().setSelectedItem((Object) p.getProvincia());
        direccion.getComuna().setSelectedItem((Object) p.getComuna());
        direccion.getSector().setText(p.getSector());
        direccion.getCalle().setText(p.getCalle());
        direccion.getNumero().setText(p.getNumero());
        direccion.getDepartamento().setText(p.getDepartamento());
        direccion.getBloque().setText(p.getBloque());
        telefono.getTelefono().setText(p.getTelefono());


    }

    public void llenarCamposAgregar(service.Paciente p) {
        mostrarCampos();
        this.limpiarCamposAutomaticos();
        rut.getRut().setText(p.getRut());
        campoNombres.setText(p.getNombres());
        campoApellidoPat.setText(p.getApellidoPaterno());
        campoApellidoMat.setText(p.getApellidoMaterno());
        prevision.setText(p.getPrevision());
        fechaNacimiento.setText(p.getFechaNac());
        direccion.getRegion().setSelectedItem((Object) p.getRegion());
        direccion.getProvincia().setSelectedItem((Object) p.getProvincia());
        direccion.getComuna().setSelectedItem((Object) p.getComuna());
        direccion.getSector().setText(p.getSector());
        direccion.getCalle().setText(p.getCalle());
        direccion.getNumero().setText(p.getNumero());
        direccion.getDepartamento().setText(p.getDepartamento());
        direccion.getBloque().setText(p.getBloque());
        telefono.getTelefono().setText(p.getTelefono());
        this.desde.setEnabled(false);
        this.hasta.setEnabled(false);
        this.agregarPrograma1.setEnabled(false);
        this.modificarPrograma1.setEnabled(false);


    }

    public void limpiarCampos() {
        //datos paciente
        rut.getRut().setText("");
        campoNombres.setText("");
        campoApellidoPat.setText("");
        campoApellidoMat.setText("");
        prevision.setText("");
        fechaNacimiento.setText("");
        telefono.getTelefono().setText("");
        fechaIngreso.setDate(null);
        //datos direccion
        direccion.getRegion().setSelectedItem((Object) "Seleccionar");
        direccion.getProvincia().setSelectedItem((Object) "Seleccionar");
        direccion.getComuna().setSelectedItem((Object) "Seleccionar");
        direccion.getSector().setText("");
        direccion.getCalle().setText("");
        direccion.getNumero().setText("");
        direccion.getDepartamento().setText("");
        direccion.getBloque().setText("");
        //datos morbilidad
        this.peso.getNumeros().setText("");
        this.talla.getNumeros().setText("");
        this.imc.getNumeros().setText("");
        this.pa.getNumeros().setText("");
        this.fc.getNumeros().setText("");
        this.temperatura.getNumeros().setText("");
        //otros
        this.desde.setDate(null);
        this.hasta.setDate(null);
        this.alergias.setText("");
        this.antecedentes.setText("");
        this.diagnostico.setText("");
        this.indicaciones.setText("");
        this.limpiarTabla();

    }

    public void limpiarCamposAutomaticos() {
        campoNombres.setText("");
        campoApellidoPat.setText("");
        campoApellidoMat.setText("");
        prevision.setText("");
        fechaNacimiento.setText("");
        telefono.getTelefono().setText("");
        //datos direccion
        direccion.getRegion().setSelectedItem((Object) "Seleccionar");
        direccion.getProvincia().setSelectedItem((Object) "Seleccionar");
        direccion.getComuna().setSelectedItem((Object) "Seleccionar");
        direccion.getSector().setText("");
        direccion.getCalle().setText("");
        direccion.getNumero().setText("");
        direccion.getDepartamento().setText("");
        direccion.getBloque().setText("");
    }

    public void inhabilitarCampos() {
        ocultarCampos();
        rut.getRut().setEnabled(false);
        fechaIngreso.setEnabled(false);
        this.peso.getNumeros().setEditable(false);
        this.talla.getNumeros().setEditable(false);
        this.imc.getNumeros().setEditable(false);
        this.pa.getNumeros().setEditable(false);
        this.fc.getNumeros().setEditable(false);
        this.temperatura.getNumeros().setEditable(false);
        this.alergias.setEditable(false);
        this.antecedentes.setEditable(false);
        this.diagnostico.setEditable(false);
        this.indicaciones.setEditable(false);
//        this.desde.setEnabled(false);
//        this.hasta.setEnabled(false);
        this.agregarPrograma1.setEnabled(false);
        this.modificarPrograma1.setEnabled(false);
    }
    /*
     * innavilita los campos generados automaticos al paciente
     */

    public void inhabilitarCamposAutomaticos() {
        campoNombres.setEditable(false);
        campoApellidoPat.setEditable(false);
        campoApellidoMat.setEditable(false);
        prevision.setEditable(false);
        fechaNacimiento.setEditable(false);
        telefono.getTelefono().setEditable(false);

        //datos direccion
        direccion.getRegion().setEditable(false);
        direccion.getRegion().setEnabled(false);
        direccion.getProvincia().setEditable(false);
        direccion.getProvincia().setEnabled(false);
        direccion.getComuna().setEditable(false);
        direccion.getComuna().setEnabled(false);
        direccion.getSector().setEditable(false);
        direccion.getCalle().setEditable(false);
        direccion.getNumero().setEditable(false);
        direccion.getDepartamento().setEditable(false);
        direccion.getBloque().setEditable(false);
    }

    public void habilitarCampos() {
        mostrarCampos();
        // datos paciente
        fechaIngreso.setEnabled(true);
        this.peso.getNumeros().setEditable(true);
        this.talla.getNumeros().setEditable(true);
        this.imc.getNumeros().setEditable(true);
        this.pa.getNumeros().setEditable(true);
        this.fc.getNumeros().setEditable(true);
        this.temperatura.getNumeros().setEditable(true);
        //otros
        this.alergias.setEditable(true);
        this.antecedentes.setEditable(true);
        this.diagnostico.setEditable(true);
        this.indicaciones.setEditable(true);
        this.desde.setEnabled(true);
        this.hasta.setEnabled(true);
        this.agregarPrograma1.setEnabled(true);
        this.modificarPrograma1.setEnabled(true);

    }

    public void agregarFocusListenerRutPaciente() {
        rut.getRut().addFocusListener(new FocusListener() {

            @Override
            public void focusGained(FocusEvent fe) {
            }

            @Override
            public void focusLost(FocusEvent fe) {
                if (rut.isValido()) {
                    service.Paciente p = (service.Paciente) cargarPaciente(rut.getRut().getText());
                    if (p != null) {
                        llenarCamposAutomaticos(p);
                        mensajeriaInformacion.setText("Área de mensajería");
                    } else {
                        rut.getRut().requestFocus();
                        limpiarCamposAutomaticos();
                        mensajeriaInformacion.setText("El rut de paciente ingresado no se encuentra en el sistema");
                        mensajeriaInformacion.setForeground(Color.red);

                    }
                } else {
                    rut.getRut().requestFocus();
                    limpiarCamposAutomaticos();
                    mensajeriaInformacion.setText("Rut  de paciente inválido");
                    mensajeriaInformacion.setForeground(Color.red);
                }
            }
        });
    }

    public void actualizarTabla() {
        this.limpiarTabla();
        List<service.EvolucionMedicoGeneral> evoluciones = listarEvolucionMedicoGeneral();
        Ordenar.ordena(evoluciones, "sesion");
        int j = 0;
        int k = 0;
        for (int i = 0; i < evoluciones.size(); i++) {
            // si la evolucion corresponde a la ficha creada
            if (evoluciones.get(i).getIdFichaMedicoGeneral().equals(this.idFicha)) {
                this.agregarFila();
                tablaEvoluciones.setValueAt(evoluciones.get(i).getId() + "", j, 0);
                tablaEvoluciones.setValueAt(evoluciones.get(i).getSesion(), j, 1);
                tablaEvoluciones.setValueAt(evoluciones.get(i).getFecha() + "", j, 2);
                tablaEvoluciones.setValueAt(evoluciones.get(i).getComentario() + "", j, 3);
                j++;
            }

        }
    }

    public int contarSesiones() {
        List<service.EvolucionMedicoGeneral> evoluciones = listarEvolucionMedicoGeneral();
        int j = 0;
        for (int i = 0; i < evoluciones.size(); i++) {
            // si la evolucion corresponde a la ficha creada
            if (evoluciones.get(i).getIdFichaMedicoGeneral().equals(this.idFicha)) {
                j++;
            }

        }
        return j;

    }

    public void ocultarColumnaID() {
        tablaEvoluciones.getColumnModel().getColumn(0).setMaxWidth(0);
        tablaEvoluciones.getColumnModel().getColumn(0).setMinWidth(0);
        tablaEvoluciones.getColumnModel().getColumn(0).setPreferredWidth(0);
        tablaEvoluciones.getColumnModel().getColumn(1).setMaxWidth(70);
        tablaEvoluciones.getColumnModel().getColumn(1).setMinWidth(70);
        tablaEvoluciones.getColumnModel().getColumn(1).setPreferredWidth(70);
        tablaEvoluciones.getColumnModel().getColumn(2).setMaxWidth(70);
        tablaEvoluciones.getColumnModel().getColumn(2).setMinWidth(70);
        tablaEvoluciones.getColumnModel().getColumn(2).setPreferredWidth(70);
    }

    public void limpiarTabla() {
        DefaultTableModel temp = (DefaultTableModel) tablaEvoluciones.getModel();
        for (int i = tablaEvoluciones.getRowCount() - 1; i >= 0; i--) {
            temp.removeRow(i);
        }
    }

    public void agregarFila() {
        DefaultTableModel temp = (DefaultTableModel) tablaEvoluciones.getModel();
        Object nuevo[] = {"", "", "", ""};
        temp.addRow(nuevo);
    }

    public void ocultarCampos() {
        this.jLabel14.setVisible(false);
        this.mensajeriaInformacion.setVisible(false);
        this.jLabel5.setVisible(false);
        this.jLabel6.setVisible(false);
    }

    public void mostrarCampos() {
        this.jLabel14.setVisible(true);
        this.jLabel5.setVisible(true);
        this.jLabel6.setVisible(true);
        this.mensajeriaInformacion.setVisible(true);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton agregarPrograma1;
    private javax.swing.JTextArea alergias;
    private javax.swing.JTextArea antecedentes;
    private javax.swing.JButton botonAceptar;
    private javax.swing.JButton botonCancelar;
    private javax.swing.JTextField campoApellidoMat;
    private javax.swing.JTextField campoApellidoPat;
    private javax.swing.JTextField campoNombres;
    private com.toedter.calendar.JDateChooser desde;
    private javax.swing.JTextArea diagnostico;
    private componentes.Direccion direccion;
    private componentes.Numeros fc;
    private com.toedter.calendar.JDateChooser fechaIngreso;
    private javax.swing.JTextField fechaNacimiento;
    private com.toedter.calendar.JDateChooser hasta;
    private componentes.Numeros imc;
    private javax.swing.JTextArea indicaciones;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel22;
    private javax.swing.JLabel jLabel23;
    private javax.swing.JLabel jLabel24;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JLabel mensajeriaInformacion;
    private javax.swing.JButton modificarPrograma1;
    private componentes.Numeros pa;
    private componentes.Numeros peso;
    private javax.swing.JTextField prevision;
    private componentes.Rut rut;
    private javax.swing.JTable tablaEvoluciones;
    private componentes.Numeros talla;
    private componentes.Telefono telefono;
    private componentes.Numeros temperatura;
    private javax.swing.JButton verEvolucion;
    // End of variables declaration//GEN-END:variables

    private static Object cargarPaciente(java.lang.String rut) {
        service.PacienteWS_Service service = new service.PacienteWS_Service();
        service.PacienteWS port = service.getPacienteWSPort();
        return port.cargarPaciente(rut);
    }

    private static Long registrar(service.Usuario usuario, java.lang.String modulo, java.lang.String accion, java.lang.String valorAnterior, java.lang.String valorNuevo) {
        service.BitacoraWSService service = new service.BitacoraWSService();
        service.BitacoraWS port = service.getBitacoraWSPort();
        return port.registrar(usuario, modulo, accion, valorAnterior, valorNuevo);
    }

    private static Object cargarPrivilegios(java.lang.String rut) {
        service.PrivilegiosWS_Service service = new service.PrivilegiosWS_Service();
        service.PrivilegiosWS port = service.getPrivilegiosWSPort();
        return port.cargarPrivilegios(rut);
    }

    private static boolean agregarFichaFarfan(service.FichaMedicoGeneral fichaFarfan) {
        service.FichaMedicoGeneralWSService service = new service.FichaMedicoGeneralWSService();
        service.FichaMedicoGeneralWS port = service.getFichaMedicoGeneralWSPort();
        return port.agregarFichaFarfan(fichaFarfan);
    }

    private static boolean editarFichaFarfan(service.FichaMedicoGeneral fichaFarfan) {
        service.FichaMedicoGeneralWSService service = new service.FichaMedicoGeneralWSService();
        service.FichaMedicoGeneralWS port = service.getFichaMedicoGeneralWSPort();
        return port.editarFichaFarfan(fichaFarfan);
    }

    private static Object obtenerFichaFarfan(java.lang.Long idFicha) {
        service.FichaMedicoGeneralWSService service = new service.FichaMedicoGeneralWSService();
        service.FichaMedicoGeneralWS port = service.getFichaMedicoGeneralWSPort();
        return port.obtenerFichaFarfan(idFicha);
    }

    private static java.util.List<service.FichaMedicoGeneral> listarFichasFarfan() {
        service.FichaMedicoGeneralWSService service = new service.FichaMedicoGeneralWSService();
        service.FichaMedicoGeneralWS port = service.getFichaMedicoGeneralWSPort();
        return port.listarFichasFarfan();
    }

    private static boolean agregarEvolucionMedicoGeneral(service.EvolucionMedicoGeneral evo) {
        service.EvolucionMedicoGeneralWSService service = new service.EvolucionMedicoGeneralWSService();
        service.EvolucionMedicoGeneralWS port = service.getEvolucionMedicoGeneralWSPort();
        return port.agregarEvolucionMedicoGeneral(evo);
    }

    private static java.util.List<service.EvolucionMedicoGeneral> listarEvolucionMedicoGeneral() {
        service.EvolucionMedicoGeneralWSService service = new service.EvolucionMedicoGeneralWSService();
        service.EvolucionMedicoGeneralWS port = service.getEvolucionMedicoGeneralWSPort();
        return port.listarEvolucionMedicoGeneral();
    }

    private static boolean eliminarEvolucionMedicoGeneral(java.lang.Long id) {
        service.EvolucionMedicoGeneralWSService service = new service.EvolucionMedicoGeneralWSService();
        service.EvolucionMedicoGeneralWS port = service.getEvolucionMedicoGeneralWSPort();
        return port.eliminarEvolucionMedicoGeneral(id);
    }

    private static Object cargarEvolucionMedicoGeneral(java.lang.Long id) {
        service.EvolucionMedicoGeneralWSService service = new service.EvolucionMedicoGeneralWSService();
        service.EvolucionMedicoGeneralWS port = service.getEvolucionMedicoGeneralWSPort();
        return port.cargarEvolucionMedicoGeneral(id);
    }

    private static boolean editarEvolucionMedicoGeneral(service.EvolucionMedicoGeneral evo) {
        service.EvolucionMedicoGeneralWSService service = new service.EvolucionMedicoGeneralWSService();
        service.EvolucionMedicoGeneralWS port = service.getEvolucionMedicoGeneralWSPort();
        return port.editarEvolucionMedicoGeneral(evo);
    }

    private static Object cargarUsuario(java.lang.String rut) {
        service.UsuarioWSService service = new service.UsuarioWSService();
        service.UsuarioWS port = service.getUsuarioWSPort();
        return port.cargarUsuario(rut);
    }
}
